<template>
  <div ref="pieCharts" :style="{ 'width': width, 'height': height }"></div>
</template>

<script>
import * as echarts from 'echarts';
import macarons from './macarons.json';
import { on, off } from "@/utils";

export default {
  name: 'PieChart',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    height: {
      type: String,
      default: '480px'
    },
    width: {
      type: String,
      default: '100%'
    },
    chartData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      pieCharts: null
    };
  },
  methods: {
    initChart() {
      this.pieCharts = echarts.init(this.$refs.pieCharts, 'macarons');
      this.setOption(this.chartData);
    },
    setOption({title, subTitle, series} = {}) {
      const option = {
        title: {
          text: title,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: series
      };
      // 设置副标题
      if (subTitle && subTitle !== '') {
        option.title.subtext = subTitle;
        option.legend.top = '48';
        option.grid.top = '88';
      }
      this.pieCharts.setOption(option);
    },
    resize() {
      this.pieCharts.resize();
    },
    showLoading() {
      this.pieCharts && this.pieCharts.showLoading();
    },
    hideLoading() {
      this.pieCharts && this.pieCharts.hideLoading();
    }
  },
  watch: {
    chartData: {
      handler(val) {
        this.pieCharts.clear();
        this.setOption(val);
      },
      deep: true
    },
    loading(val) {
      if (val) {
        this.showLoading();
      } else {
        this.hideLoading();
      }
    }
  },
  mounted() {
    echarts.registerTheme('macarons', macarons.theme);
    this.$nextTick(() => {
      this.initChart();
      on(window, 'resize', this.resize);
    });
  },
  beforeDestroy() {
    off(window, 'resize', this.resize);
    if (!this.pieCharts) {
      return;
    }
    this.pieCharts.dispose();
    this.pieCharts = null;
  },
};
</script>

<style scoped>

</style>
